#include "bofugui.h"
#include "ui_bofugui.h"


QString output="transcription.txt";    //Name of the transcriptionfile

/*
 *To select existing folders
 */
void BofuGui::selectionHandle(const QItemSelection &selected, const QItemSelection &deselected)
{
    QString name;
    deselected.isEmpty(); //removes the Warning, that deselected isn't used

    if (!selected.isEmpty()){   //prevents index out of bounds errors when deleting a folder
        name = QString(selected.indexes()[0].data().toString());
        //writeToLog("echo \"Selected: "+name+"\"");
        ui->lineEdit->setText(name);
    }
}

/*
 *Mainwidget
 */

BofuGui::BofuGui(QWidget *parent) :
        QMainWindow(parent),
        ui(new Ui::BofuGui)
{
    exe=QCoreApplication::applicationDirPath();
    //Initiating GUI
    QFile in(exe.absolutePath()+"/.data/images/boss.png");
    if ( in.open(QIODevice::ReadOnly)) {
        ui->setupUi(this);
    }   else{
        QMessageBox::information(this,"Wrong program execution","<p>Please start this GUI from a shell:</p> <p>\'cd\' into the program folder and execute with \'./BOFU-GUI\'</p><p>Probably not all necessary files are in the programfolder!</p>");

    }

    ui->lineEdit->setFocus();

    /*
     *To show existing Projects
     */
    model = new QFileSystemModel;
    dir = ( (exe.absolutePath()+"/bofu-project/") );
    if (!dir.exists())
    {
        dir.mkpath("../bofu-project");
    }

    bofu = ( (exe.absolutePath()+"/.data/bofu") );

    model->setRootPath(dir.absolutePath());
    ui->listView->setModel(model);
    ui->listView->setRootIndex(model->index(dir.path()));
    ui->listView->setSelectionMode(QAbstractItemView::SingleSelection);

    /*
     *MainGui begin
     */
    ui->statusBar->showMessage(tr("Ready"));
    QRegExp regExp("[A-Za-z_0-9]{3,20}");           //Not every symbol as foldername allowed
    ui->lineEdit->setValidator(new QRegExpValidator(regExp, this));
    connect(ui->listView->selectionModel(), SIGNAL(selectionChanged(const QItemSelection &,
                                                                    const QItemSelection &)),
            this, SLOT(selectionHandle(const QItemSelection &,
                                       const QItemSelection &)));
    connect(ui->listView, SIGNAL(doubleClicked(QModelIndex)),
            this, SLOT(on_korpusNameButton_clicked()));
    connect(ui->lineEdit , SIGNAL(textChanged(const QString &)), this, SLOT(enableSafeButton(const QString &)));
    connect(ui->lineEdit_synth , SIGNAL(textChanged(const QString &)), this, SLOT(enableSynthButton(const QString &)));
    connect(ui->plainTextEdit_Diary , SIGNAL(textChanged()), this, SLOT(enableDiarySafeButton()));
    connect(ui->plainTextEdit_multisynth , SIGNAL(textChanged()), this, SLOT(enableMultiSynthButton()));
    connect(ui->action_ber_BOFU_GUI , SIGNAL(triggered()), this, SLOT(about()));
    connect(ui->actionKorpus_Erstellung , SIGNAL(triggered()), this, SLOT(on_actionKorpus_Erstellung_triggered()));
    QPixmap bosslogo(exe.absolutePath()+"/.data/images/boss.png");
    ui->image->setPixmap( bosslogo );

    //removing all tabs except 'Welcome'
    ui->tabWidget->removeTab(9);
    ui->tabWidget->removeTab(8);
    ui->tabWidget->removeTab(7);
    ui->tabWidget->removeTab(6);
    ui->tabWidget->removeTab(5);
    ui->tabWidget->removeTab(4);
    ui->tabWidget->removeTab(3);
    ui->tabWidget->removeTab(2);
    ui->tabWidget->removeTab(1);
    ui->dockWidget->hide();
    readSettings();

}

BofuGui::~BofuGui()
{
    delete ui;
    delete model;

}

void BofuGui::changeEvent(QEvent *e)
{
    QMainWindow::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        ui->retranslateUi(this);
        break;
    default:
        break;
    }
}

/*
 *Small Widgets
 */
void BofuGui::about()
{
    QMessageBox::about(this, (QString::fromUtf8("Über BOFU-GUI")),
                       QString::fromUtf8("<h2>BOFU-GUI 0.9a</h2>"
                                         "<p>Copyright &copy; 2010 IKP Universitaet Bonn</p>"
                                         "<p>The BOFU-GUI is a graphical user interface"
                                         " for the BOFU tools, which can be used for "
                                         " the creation of speechcorpora.</p>"
                                         "<p>It includes Lam4HTK, which is a speech aligner that uses HTK as backend.</p>"));
}

void BofuGui::errorFiles()
{
    QMessageBox::warning(this, (QString::fromUtf8("Error")),
                         QString::fromUtf8("<h2>Missing file(s)</h2>"
                                           "<p>One or more files for the command execution are missing!</p>"
                                           "<p>Please check the folder contents.</p>"));
}

void BofuGui::scriptDone()
{
    QMessageBox::information(this, (QString::fromUtf8("Information")),
                             QString::fromUtf8("<h2>Script finished</h2>"
                                               "<p>Please check the terminal for errors.</p>"));
}

/******************************************************************************************************/

void BofuGui::enableAll()
{
    ui->tabWidget->insertTab(1, ui->tab_step1, "Step 1"); // The tab is added back.
    ui->tabWidget->insertTab(2, ui->tab_step2, "Step 2"); // The tab is added back.
    ui->tabWidget->insertTab(3, ui->tab_allignment, "Allignment"); // The tab is added back.
    ui->tabWidget->insertTab(4, ui->tab_step3, "Step 3"); // The tab is added back.
    ui->tabWidget->insertTab(5, ui->tab_MySQL, "MySQL"); // The tab is added back.
    ui->tabWidget->insertTab(6, ui->tab_step4, "Step 4"); // The tab is added back.
    ui->tabWidget->insertTab(7, ui->tab_synth, "Synth"); // The tab is added back.
    ui->tabWidget->insertTab(8, ui->tab_Diary, "Diary"); // The tab is added back.
    ui->action_Export_active_project->setEnabled(1);
    ui->guidedBox->setEnabled(0);
    ui->pushButton_createFileList->setEnabled(1);
    ui->tabWidget->removeTab(0);
    ui->deleteButton->setEnabled(1);
    ui->showFolderButton->setEnabled(1);
    ui->lab2blfButton->setEnabled(1);
    ui->blf2xmlButton->setEnabled(1);
    ui->addPhrasesButton->setEnabled(1);
    ui->alignFlagButton->setEnabled(1);
    ui->editContextButton->setEnabled(1);
    ui->addContextButton->setEnabled(1);
    ui->addHPButton->setEnabled(1);
    ui->optBoundsButton->setEnabled(1);
    ui->getF0BossButton->setEnabled(1);
    ui->addF0Button->setEnabled(1);
    ui->addmelboundsButton->setEnabled(1);
    ui->exportButton->setEnabled(1);
    ui->pushButton_importUnitlist->setEnabled(1);
    ui->lab2blfButton->setEnabled(1);
    ui->decodingButton->setEnabled(1);
    ui->wav2rawButton->setEnabled(1);
    ui->raw2wavButton->setEnabled(1);
    ui->korpusNameButton->setEnabled(0);
    ui->newButton->setEnabled(1);
    ui->lineEdit->setEnabled(0);
    ui->pushButton_importFileList->setEnabled(1);

    ui->pushButton_importOrthographic->setEnabled(1);
    ui->pushButton_importTranscription->setEnabled(1);
    ui->lexiconLoadButton->setEnabled(1);
    ui->pushButton_loadWav->setEnabled(1);
    ui->labelimportButton->setEnabled(1);
    ui->labelimportButton_2->setEnabled(1);
    ui->codingButton->setEnabled(1);
    ui->pushButton_createDict->setEnabled(1);
    ui->pushButton_refreshfolder->setEnabled(1);

    ui->pushButton_showLog->setEnabled(1);

}

/***********************************************************************************/
//Menu-items

void BofuGui::on_actionKorpus_Erstellung_triggered()
{
    openURL(QUrl( "./.data/doku/bofu-doku.pdf" ));
}

void BofuGui::on_actionBOSS_Doku_triggered()
{
    openURL(QUrl( "./.data/doku/BOSS_User_Manual.pdf" ));

}

void BofuGui::on_actionBeenden_triggered()
{
}
/***********************************************************************************/

// TODO
void BofuGui::guided()
{
    ui->deleteButton->setEnabled(1);
    ui->showFolderButton->setEnabled(1);
    ui->korpusNameButton->setEnabled(0);
    ui->newButton->setEnabled(1);
    ui->lineEdit->setEnabled(0);
}


void BofuGui::on_pushButton_showLog_clicked()
{
    if (ui->dockWidget->isHidden()){
        ui->dockWidget->show();

    }
    else {
        ui->dockWidget->hide();

    }
}

//Check for installed 3rd-party software
void BofuGui::on_pushButton_checkCMDs_clicked()
{
    int res;
    QString resultString;
    QString* softwareCheck[8][2] = {
        {new QString("BOSS"),	new QString("boss_g2p_de --version >/dev/null 2>&1")},
        {new QString("SOX"),	new QString("sox --version >/dev/null 2>&1")},
        {new QString("SED"),	new QString("sed --version >/dev/null 2>&1")},
        {new QString("RECODE"),	new QString("recode --version >/dev/null 2>&1")},
        {new QString("SPEECHTOOLS"),	new QString("wagon -h >/dev/null 2>&1")},
        {new QString("HTK"),	new QString("HCopy >/dev/null 2>&1")},
        {new QString("PERL"),	new QString("perl -V >/dev/null 2>&1")},
        {new QString("TCLSH"),	new QString("man tclsh >/dev/null 2>&1")},
    };
    for(int i=0;i<8;i++){
        res = system(softwareCheck[i][1]->toUtf8());
        if ( WEXITSTATUS(res) != 0 ) {
            resultString.append(softwareCheck[i][0]->toUtf8()+": <font color=\"red\">*not installed*</font><br />");
        }
        else{
            resultString.append(softwareCheck[i][0]->toUtf8()+": <font color=\"green\">*installed*</font><br />");
        }
    }
    QMessageBox::information(this, (QString::fromUtf8("Installed Software")),
                             QString::fromUtf8("<h2>Check result:</h2>"
                                               "<p>"+resultString.toUtf8()+
                                               "for f0-extraction please also check that \"libsnack2(-alsa)\" is installed!</p>"));
}

void BofuGui::waitSecs(int time){
    QTime dieTime = QTime::currentTime().addSecs(time);
    while( QTime::currentTime() < dieTime )
        QCoreApplication::processEvents(QEventLoop::AllEvents, 100);
}

void BofuGui::openURL(QUrl url){
    QDesktopServices::openUrl( url );
}

void BofuGui::copyFile(QString source, QString target){
    bool copyDone;
    QFile dest;
    dest.setFileName(target);
    if (dest.exists())
    {
        int del = QMessageBox::question(this, tr("Destination File already exists"),
                                        tr("<p>If you continue, the File will be overwritten!</p>"
                                           "<p>Do you want to continue?</p>"),
                                        QMessageBox::Yes | QMessageBox::No);
        if (del == QMessageBox::Yes) {
            dest.remove();
            copyDone = QFile::copy( source , target );
        } else if (del == QMessageBox::No) {
            //do nothing
        }
    } else{
        dest.remove();
        copyDone = QFile::copy( source , target );
    }
    if (copyDone==false){
        qDebug("Error writing File");
    }
}



